﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace MengCC.Core.Plugins
{
    internal class PluginDowloader
    {
        private string pluginTempDir;
        private static Dictionary<string, bool> tastList;
        private static GitDownloader gitDownloader;
        static PluginDowloader()
        {
            tastList = new Dictionary<string, bool>();
            gitDownloader = new GitDownloader();
        }

        public PluginDowloader(string pluginTempDir)
        {
            this.pluginTempDir = pluginTempDir;
        }

        public bool AddTask(PluginDownloadConfig pluginDownloadConfig)
        {
            lock("PluginDowloader-AddTask")
            {
                if (tastList.ContainsKey(pluginDownloadConfig.Name)) return false;
                tastList.Add(pluginDownloadConfig.Name, false);
            }
            //TODO 开启异步下载任务
            RunDownloadTask(pluginDownloadConfig);
            return true;

        }

        private async Task RunDownloadTask(PluginDownloadConfig pluginDownloadConfig)
        {
            await Task.Delay(0);
            var pluginName = $"{pluginDownloadConfig.Name}_{pluginDownloadConfig.Platform}";
            gitDownloader.Download(Path.Combine(pluginTempDir, pluginName), pluginDownloadConfig.RemoteUrl, "master");
            tastList[pluginName] =true;
        }

        /// <summary>
        /// 获取下载状态
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool HasDownloaded(string key)
        {
            return tastList[key];
        }

        /// <summary>
        /// 清除记录
        /// </summary>
        /// <param name="key"></param>
        public void Clear()
        {
            foreach (var item in tastList.Keys)
            {
                tastList.Remove(item);
            }
        }

    }
}
